import { inject, h } from "vue"
import { WebExcelCell } from "./cell"
import { checkTargetSlotIsEmpty } from "./util"
import { logInfo } from "./log"
import { ProvideEditStateKey } from "./keys"

function WebExcelHead(props: Props, { slots }) {
    const { checkDoingEdit, checkReadyEdit } = inject(ProvideEditStateKey) as EditCellStateResult

    const rowIndex = -1;

    const cells = props.columns?.map((column, colindex) => {
        return h(WebExcelCell, {
            class: 'cell head',
            column: column,
            colIndex: colindex,
            rowIndex: rowIndex
        }, {
            default: () => {
                const props = {
                    column,
                    title: column.title,
                    dataIndex: column.dataIndex,
                    colindex: colindex,
                }
                
                if (slots.headerEditCell){
                    if (checkDoingEdit(rowIndex, colindex) && checkTargetSlotIsEmpty(slots.headerEditCell?.(props))) return undefined;
                }
                
                const slotDefault = slots.headerCell?.(props)
                return !checkTargetSlotIsEmpty(slotDefault) ? slotDefault : column.title
            },
            editCell: () => {

                if (checkReadyEdit(rowIndex, colindex)) return undefined;

                const props = {
                    column,
                    title: column.title,
                    dataIndex: column.dataIndex,
                    colindex: colindex,
                }
                return slots.headerEditCell?.(props)
            }
        })
    })

    if (props.showIndex) {
        cells.unshift(h(
            WebExcelCell, 
            {
                class: 'cell head row-index',
                column: { readonly: true },
                colIndex: undefined,
                rowIndex: rowIndex
            },
            {
                default: () => slots.headerIndex?.()
            }
        ))
    }

    return cells
}


export { WebExcelHead }